package com.nineclock.auth.processor.impl;

import cn.hutool.core.util.StrUtil;
import com.nineclock.auth.entity.IntegrationAuthenticationEntity;
import com.nineclock.auth.processor.AuthenticationProcessor;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.system.dto.SysUserDTO;
import com.nineclock.system.feign.SysUserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * 该自定义认证器，主要用于实现 用户名/手机号-密码的方式认证。
 *  在该认证方式下，前端传递的参数auth_type值为空
 */
@Component
public class UsernameAndPasswordAuthenticationProcessor implements AuthenticationProcessor {
    @Autowired
    private SysUserFeign sysUserFeign;
    @Override
    public SysUserDTO authenticate(IntegrationAuthenticationEntity entity) {
        String usernae = entity.getAuthParameter("username");
        String password = entity.getAuthParameter("password");

        if (usernae == null || password == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        SysUserDTO sysUserDTO = sysUserFeign.queryUser(usernae).getData();
            if (sysUserDTO == null){
                throw new NcException(ResponseEnum.INVALID_USERNAME_PASSWORD);
            }
        return sysUserDTO;
    }

    @Override
    public boolean support(IntegrationAuthenticationEntity entity) {
        if (entity!=null && StrUtil.isEmpty(entity.getAuthType())){
            return  true;
        }
        return false;
    }
}
